from selenium import webdriver

from utils.read_config import ini
from utils.logger import Log
from global_conf import config
import os

log = Log(os.path.basename(__file__))

class GetDriver(object):

    driver = None

    @classmethod
    def get_driver(cls):

        if cls.driver is None:

            browser_type = ini.browser_type

            if  browser_type == "chrome":

                options = webdriver.ChromeOptions()
                options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
                options.add_argument('--ignore-certificate-errors') # 忽略证书错误
                options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
                options.add_argument('--disable-infobars')  # 禁止策略化
                options.add_argument('--disable-dev-shm-usage')
                options.add_argument('--disable-features=NetworkService')
                options.add_argument("--disable-features=VizDisplayCompositor")
                cls.driver = webdriver.Chrome(executable_path=config.DRIVER_PATH, options=options)

            elif  browser_type == "firefox":
                cls.driver = webdriver.Firefox()

            elif  browser_type == "ie":
                cls.driver = webdriver.Ie()

            elif browser_type == "edge":
                cls.driver = webdriver.Edge()

            elif browser_type == "chrome_headless":
                chrome_options = webdriver.ChromeOptions()
                chrome_options.add_argument('--headless')
                cls.driver = webdriver.Chrome(chrome_options=chrome_options)

            else:
                log.error("找不到{0}浏览器, 应从中选取一个:'ie', 'ff', 'opera', 'edge', 'chrome' , 'chrome_headless'".format(browser_type))

            cls.driver.maximize_window()
            cls.driver.implicitly_wait(config.IMPLICITLY_WAIT_TIME)

        return cls.driver

    @classmethod
    def close(cls):

        if cls.driver is not None:
            cls.driver.quit()
            cls.driver = None

driver = GetDriver().get_driver()
